package com.lishem.top100._02doublepointer;

/**
 * https://leetcode.cn/problems/container-with-most-water/
 * <p>
 * 给定一个长度为 n 的整数数组 height 。有 n 条垂线，第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
 * <p>
 * 找出其中的两条线，使得它们与 x 轴共同构成的容器可以容纳最多的水。
 * <p>
 * 返回容器可以储存的最大水量。
 * <p>
 * 说明：你不能倾斜容器。
 */
public class _02LetCode11_盛最多水的容器 {

    // 再次优化
    public int maxArea2(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int max = 0;
        while (left < right) {
            int curShortHeight = Math.min(height[left], height[right]);
            int area = curShortHeight * (right - left);
            max = Math.max(max, area);
            if (height[left] < height[right]) {
                while (left < right && height[left] <= curShortHeight) {
                    left++;
                }
            } else {
                while (left < right && height[right] <= curShortHeight) {
                    right--;
                }
            }
        }
        return max;
    }

    public int maxArea1(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int max = 0;
        while (left < right) {
            int area = Math.min(height[left], height[right]) * (right - left);
            max = Math.max(max, area);
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return max;
    }

    public static void main(String[] args) {
        _02LetCode11_盛最多水的容器 sol = new _02LetCode11_盛最多水的容器();
        System.out.println(sol.maxArea1(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));
        System.out.println(sol.maxArea1(new int[]{1, 1}));


        System.out.println(sol.maxArea2(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));
        System.out.println(sol.maxArea2(new int[]{1, 1}));
    }
}
